import logging
import sys
from pathlib import Path
from typing import Optional
from logging.handlers import RotatingFileHandler


class LogConfig:
    """统一日志配置类"""

    def __init__(
        self,
        log_level: str = "INFO",
        log_format: Optional[str] = None,
        log_file: Optional[str] = None,
        max_file_size: int = 10 * 1024 * 1024,  # 10MB
        backup_count: int = 5,
        enable_console: bool = True,
        enable_file: bool = True
    ):
        self.log_level = getattr(logging, log_level.upper())
        self.log_format = log_format or (
            "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] - %(message)s"
        )
        self.log_file = log_file or "logs/app.log"
        self.max_file_size = max_file_size
        self.backup_count = backup_count
        self.enable_console = enable_console
        # 文件日志开关，直接采用传入值
        self.enable_file = enable_file

        # 确保日志目录存在
        if self.enable_file:
            log_dir = Path(self.log_file).parent
            log_dir.mkdir(parents=True, exist_ok=True)


    def setup_logging(self):
        """设置日志配置"""
        # 创建格式化器
        formatter = logging.Formatter(self.log_format)

        if self.enable_file:
            print(f"[LOG CONFIG] File logging enabled: {self.log_file}")

        # 获取根日志器
        root_logger = logging.getLogger()
        root_logger.setLevel(self.log_level)

        # 清除现有的处理器，防止重复添加
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)

        # 控制台处理器
        if self.enable_console:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setLevel(self.log_level)
            console_handler.setFormatter(formatter)
            # 设置控制台输出编码
            if hasattr(console_handler.stream, 'reconfigure'):
                console_handler.stream.reconfigure(encoding='utf-8')
            root_logger.addHandler(console_handler)

        # 文件处理器（带轮转）
        if self.enable_file:
            file_handler = RotatingFileHandler(
                self.log_file,
                maxBytes=self.max_file_size,
                backupCount=self.backup_count,
                encoding='utf-8'
            )
            file_handler.setLevel(self.log_level)
            file_handler.setFormatter(formatter)
            root_logger.addHandler(file_handler)

        return root_logger


def get_logger(name: str) -> logging.Logger:
    """获取指定名称的日志器"""
    return logging.getLogger(name)


# 默认日志配置
default_log_config = LogConfig()


def setup_default_logging():
    """设置默认日志配置"""
    return default_log_config.setup_logging()